#ifndef GUDB_H
#define GUDB_H

#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>

// Forward declaration for file_system
struct file_system;

// Error codes
#define GU_OK           0
#define GU_ERR_SYNTAX   1
#define GU_ERR_NOMEM    2
#define GU_ERR_IO       3
#define GU_ERR_CONFLICT 4
#define GU_ERR_AUTH     5
#define GU_ERR_PERM     6
#define GU_ERR_INTERNAL 7

// Open flags
#define GU_OPEN_CREATE    0x01
#define GU_OPEN_READWRITE 0x02
#define GU_OPEN_READONLY  0x04

// Transaction isolation levels
#define GU_TXN_RC  0  // Read Committed
#define GU_TXN_RR  1  // Repeatable Read
#define GU_TXN_SSI 2  // Serializable Snapshot Isolation

// Permission bitmask constants
#define GU_PERM_SELECT 0x01
#define GU_PERM_INSERT 0x02
#define GU_PERM_UPDATE 0x04
#define GU_PERM_DELETE 0x08
#define GU_PERM_ALL    0x0F

// Page flags
#define FLAG_DIRTY    0x01
#define FLAG_ENCRYPT  0x02
#define FLAG_COMPRESS 0x04
#define FLAG_HOT      0x08

// Configuration constants
#define GUDB_PAGE_SIZE       4096
#define GUDB_MAX_CONNECTIONS 1024
#define GUDB_MAX_USERS       1024
#define GUDB_MAX_ACTIVE_TXN  1024
#define GUDB_DEFAULT_PORT    3316
#define GUDB_PAGE_CACHE_SIZE (16 * 1024 * 1024)  // 16MB
#define GUDB_WAL_BUFFER_SIZE (8 * 1024 * 1024)   // 8MB
#define GUDB_WAL_SEGMENT_SIZE (16 * 1024 * 1024) // 16MB
#define GUDB_BINLOG_SEGMENT_SIZE (16 * 1024 * 1024) // 16MB

// Forward declarations
typedef struct gudb gudb;
typedef struct gudb_txn gudb_txn;
typedef struct result_t result_t;
typedef struct metadata_manager metadata_manager_t;

// User structure
typedef struct {
    char username[32];
    char password_hash[64];  // SHA2-256
    char role[16];           // admin, read_write, read_only
} gudb_user;

// Permission structure
typedef struct {
    char table[32];
    bool select;
    bool insert;
    bool update;
    bool delete;
} gudb_permission;

// Page structure (4KB)
typedef struct {
    uint64_t lsn;           // Log Sequence Number
    uint32_t checksum;      // CRC32
    uint8_t flags;          // Page flags
    uint16_t free_space;    // Free space in bytes
    uint8_t reserved;       // Reserved for alignment
    uint8_t data[GUDB_PAGE_SIZE - 16];  // Page data
} gudb_page;

// MVCC header (24 bytes)
typedef struct {
    uint64_t xid;           // Transaction ID
    uint64_t create_time;   // Creation timestamp
    uint64_t delete_time;   // Deletion timestamp
} mvcc_header;

// Bw-Tree node structure
typedef struct bwtree_node {
    uint32_t keys[16];              // Compressed keys
    uint32_t pointers[16];          // 4-byte pointers
    struct bwtree_delta* delta_chain; // Delta updates chain
    bool is_leaf;
    uint8_t count;                  // Number of valid entries
} bwtree_node;

// Delta update for Bw-Tree
typedef struct bwtree_delta {
    uint8_t type;                   // Insert, Delete, Split, etc.
    uint32_t key;
    uint64_t value;
    struct bwtree_delta* next;
} bwtree_delta;

// WAL record
typedef struct {
    uint64_t lsn;
    uint8_t opcode;                 // OP_INSERT, OP_UPDATE, OP_DELETE
    uint16_t data_len;
    uint8_t data[8192];
} wal_record;

// Binlog record (MySQL format)
typedef struct {
    uint64_t timestamp;
    uint16_t event_len;
    char event[8192];               // MySQL binlog format
} binlog_record;

// Statistics for embedded analytics
typedef struct {
    char table[32];
    uint64_t count;
    double sum;
    double avg;
} gudb_stats;

// Partition structure
typedef struct {
    char name[16];
    char type[8];                   // "range" or "hash"
    uint64_t boundary;
    uint64_t size;                  // Size in bytes
} gudb_partition;

// Transaction structure
struct gudb_txn {
    uint64_t xid;                   // Transaction ID
    gudb* db;                       // Database handle
    uint8_t isolation_level;
    bool read_only;
    char username[32];              // User who started the transaction
    char current_database[64];      // Current database name for this transaction
    bool database_explicitly_selected; // Whether user explicitly selected database with USE
    uint64_t start_time;
};

// Query result structure
struct result_t {
    uint32_t row_count;
    uint32_t col_count;
    char** column_names;
    char*** rows;                   // rows[row][col]
    char* error_msg;
};

// Main database handle
struct gudb {
    char data_dir[256];             // Data directory path
    struct file_system* fs;         // File system manager
    
    // Legacy file descriptors (for compatibility)
    int data_fd;                    // Data file descriptor
    int wal_fd;                     // WAL file descriptor
    int binlog_fd;                  // Binlog file descriptor
    int meta_fd;                    // Metadata file descriptor
    int log_fd;                     // Log file descriptor
    int lock_fd;                    // Lock file descriptor
    
    // Memory management
    void* memory_mgr;               // Memory manager instance
    void* page_cache;               // LRU page cache
    void* wal_buffer;               // WAL write buffer (legacy)
    void* binlog_buffer;            // Binlog write buffer
    void* wal_manager;              // WAL manager instance
    void* network_server;           // Network server instance
    
    // Storage engine
    bwtree_node* root_node;         // Bw-Tree root
    void* storage;                  // Storage engine instance (bw_tree_t*)
    
    // Metadata management
    metadata_manager_t* metadata;   // Metadata manager instance
    
    // Trigger system
    void* trigger_system;           // Trigger system instance
    
    // Transaction management
    uint64_t next_xid;              // Next transaction ID
    gudb_txn* active_txns[GUDB_MAX_ACTIVE_TXN];
    
    // User management
    gudb_user users[GUDB_MAX_USERS];
    gudb_permission permissions[GUDB_MAX_USERS * 10];  // 10 tables per user max
    
    // Configuration
    uint16_t port;
    uint32_t max_connections;
    bool tls_enabled;
    bool binlog_enabled;
    char encryption_key[32];        // AES-256 key
    
    // Statistics
    uint64_t total_queries;
    uint64_t total_errors;
    uint64_t uptime_seconds;
};

// Core API functions
gudb* gudb_open(const char* path, int flags, const char* user, const char* password);
int gudb_close(gudb* db);

// Transaction API
gudb_txn* gudb_begin(gudb* db, int isolation_level, const char* database_name);
int gudb_commit(gudb_txn* txn);
int gudb_rollback(gudb_txn* txn);

// SQL execution API
int gudb_exec(gudb_txn* txn, const char* sql, const char** params, result_t** result);
void gudb_free_result(result_t* result);

// Error handling
const char* gudb_error(gudb* db);
const char* gudb_txn_error(gudb_txn* txn);
const char* gudb_txn_current_database(gudb_txn* txn);

// User management API
int gudb_create_user(gudb* db, const char* username, const char* password, const char* role);
int gudb_grant_permission(gudb* db, const char* username, const char* table, 
                         bool select, bool insert, bool update, bool delete);

// Utility functions
int gudb_analyze_table(gudb* db, const char* table);
int gudb_checkpoint(gudb* db);
int gudb_vacuum(gudb* db);

// Server mode functions (for gudbd daemon)
int gudb_server_start(gudb* db, const char* host, uint16_t port);
int gudb_server_stop(gudb* db);

#endif // GUDB_H